﻿using Models;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.PhantomJS;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Wesley.Crawler.SimpleCrawler.Events; 

namespace Wesley.Crawler.SimpleCrawler
{
	public class AQiyiCrawler : ICrawler
	{
		public event EventHandler<OnStartEventArgs> OnStart;//爬虫启动事件

		public event EventHandler<OnCompletedEventArgs> OnCompleted;//爬虫完成事件

		public event EventHandler<OnErrorEventArgs> OnError;//爬虫出错事件

		public CookieContainer CookiesContainer { get; set; }//定义Cookie容器

		public AQiyiCrawler() { }


		/// <summary>
		/// 异步创建爬虫
		/// </summary>
		/// <param name="uri">爬虫URL地址</param>
		/// <param name="proxy">代理服务器</param>
		/// <returns>网页源代码</returns>
		public async Task<List<VideoEntity>> Start(Uri uri )
		{
			return await Task.Run(() =>
			{
				var videos = new List<VideoEntity>();

				try
				{
					var driver = new ChromeDriver(new ChromeOptions { PageLoadStrategy = OpenQA.Selenium.PageLoadStrategy.Normal });
					driver.Url = uri.ToString();
					 
					 

					var resultBody = driver.FindElementByClassName("mod_search_result");
					if (resultBody == null) return new List<VideoEntity>();
					;
					var items = resultBody.FindElements(OpenQA.Selenium.By.ClassName("list_item"));
					if (items == null) return new List<VideoEntity>();
					foreach (var item in items.Where(s => s.GetAttribute("data-widget-searchlist-catageory") == "电视剧"
					|| s.GetAttribute("data-widget-searchlist-catageory") == "电影"))
					{
						try
						{
							var video = new VideoEntity();
							video.PUrl = "0";
							video.Title = item.GetAttribute("data-widget-searchlist-tvname");
							if (item.FindElement(OpenQA.Selenium.By.TagName("a"))!=null)
							video.Url = item.FindElement(OpenQA.Selenium.By.TagName("a")).GetAttribute("href");

							switch (item.GetAttribute("data-widget-searchlist-catageory")) {
								case "电视剧":
									video.VideoType = VideoType.multiEpisode;
									break;
								case "电影":
									video.VideoType = VideoType.video;
									break;
							}

							//处理连续剧
							if (video.VideoType == VideoType.multiEpisode)
							{
								 
								var multiEpisodes = new List<VideoEntity>();

								var videosElements = item.FindElements(OpenQA.Selenium.By.ClassName("album_link"));

								if (videosElements != null)
								{
									foreach (var videoElement in videosElements)
									{
										var videoItem = new VideoEntity();
										videoItem.Title = videoElement.GetAttribute("title");
										videoItem.Url = videoElement.GetAttribute("href");
										videoItem.VideoType = VideoType.video;
										videoItem.PUrl=video.Url;
										if (!multiEpisodes.Any(s => s.Url == videoItem.Url  ))
											multiEpisodes.Add(videoItem);

									}

									videos.AddRange(multiEpisodes.Where(s => s.Title != "展开") );

								 
								}

							}

							videos.Add(video);


						}
						catch (Exception ex)
						{

							throw ex;
						}

					}

					driver.Quit();

					
				}
				catch (Exception ex)
				{
					throw ex;
				}
				return videos;
			});
		}

		 
	} 
}
